<script setup lang="ts">
import {
  IconMore,
  IconFile,
  IconCalendar,
  IconBook,
  IconCaretRight,
  IconEdit,
  IconUser,
  IconDelete
} from '@arco-design/web-vue/es/icon'
import TaskList from '@/components/tasks/TaskList.vue'
import { EDIT_STATUS, useEditStore, useUserStore } from '@/store'
import { useTeamStore } from '@/store'
import {
  onMounted,
  ref,
  onUnmounted,
  Ref,
  onActivated,
  onDeactivated,
  watch,
  computed,
  h,
  reactive,
  nextTick
} from 'vue'
import { Message, Notification } from '@arco-design/web-vue'
import { useRoute } from 'vue-router'
import { onBeforeRouteLeave } from 'vue-router'
import dayjs from 'dayjs'
import { getMembersUsingGet, getProjectUsingGet } from '@/api/projectController'
import {
  COMPLETE_STATUS_CONFIG,
  getCompleteStatus,
  getCompleteColor
} from '@/constants/CompleteStatus'
import { getTaskCountByMileIdUsingGet } from '@/api/milestoneController'
import { deleteTaskUsingDelete, updateTaskUsingPut } from '@/api/taskController'
import { getTaskPriorityColor, getPriorityLabel } from '@/constants/Priority'
import { PRIORITY_CONFIG } from '@/constants/Priority'
import TaskView from '@/components/tasks/TaskView.vue'
import RequirementView from '@/components/requirements/RequirementView.vue'
import IterationView from '@/components/iterations/IterationView.vue'
import MileStoneView from '@/components/milestones/MileStoneView.vue'
import EditIndicator from '@/components/EditIndicator.vue'
import TaskCreate from '@/components/tasks/TaskCreate.vue'
import RequirementCreate from '@/components/requirements/RequirementCreate.vue'
import IterationCreate from '@/components/iterations/IterationCreate.vue'
import MilestoneCreate from '@/components/milestones/MilestoneCreate.vue'
const userStore = useUserStore()
const teamStore = useTeamStore()
const editStore = useEditStore()
const route = useRoute()
const props = defineProps<{
  proId: number
}>()
defineOptions({
  name: 'TaskManage'
})
//#region 项目数据定义
const currentProject = ref<API.ProjectVo | null>(null)
//项目成员列表
const projectMembers = ref<API.UserVO[]>([])
const getProjectMembers = async () => {
  const res: any = await getMembersUsingGet({ id: props.proId })
  if (res.code === 0) {
    projectMembers.value = res.data
  } else {
    Message.error(res.message)
  }
}
//#endregion
//#region websocket 区域
// WebSocket 连接实例和状态管理
const ws = ref<WebSocket | null>(null) // WebSocket 连接实例
const wsConnected = ref(false) // 是否连接
const reconnectCount = ref(0) // 重连次数
const isReconnecting = ref(false) // 是否正在重连
const isNormalClosure = ref(false) // 是否是正常关闭
const MAX_RECONNECT_COUNT = 5 // 最大重连次数
const RECONNECT_INTERVAL = 3000 // 重连间隔时间
const HEARTBEAT_INTERVAL = 3000 // 3秒检测一次
const onlineUserList: Ref<CUSTOMAPI.ConnectUserModel[]> = ref([])
const totalOnline: Ref<number> = ref(0)
const connectUser: Ref<CUSTOMAPI.ConnectUserModel | null> = ref(null)
// 心跳定时器
const heartbeatTimer = ref<number | null>(null)
//table ws消息格式
const wsTableMessageModel: Ref<CUSTOMAPI.WsMessageModel> = ref({
  type: 'table',
  tableMessageModel: {
    id: 0,
    sendId: 0,
    operation: '',
    sendTime: ''
  }
})
//edit ws消息格式
const wsEditMessageModel: Ref<CUSTOMAPI.WsMessageModel> = ref({
  type: 'edit',
  editInfoModel: {
    cellId: '',
    cellName: '',
    editorInfo: {
      id: '',
      name: '',
      avatar: ''
    },
    status: ''
  }
})
//申请单元格
const handleApplyCell = (cellId: string) => {
  if (!ws.value) return
  wsEditMessageModel.value.type = 'edit'
  wsEditMessageModel.value.editInfoModel.cellId = cellId
  wsEditMessageModel.value.editInfoModel.cellName = ''
  wsEditMessageModel.value.editInfoModel.status = 'editing'
  wsEditMessageModel.value.editInfoModel.editorInfo.id = userStore.user.id as number
  wsEditMessageModel.value.editInfoModel.editorInfo.avatar = userStore.user.avatar || ''
  wsEditMessageModel.value.editInfoModel.editorInfo.name = userStore.user.username || ''
  ws.value.send(JSON.stringify(wsEditMessageModel.value))
}
//释放单元格
const handleReleaseCell = (cellId: string) => {
  if (!ws.value) return
  wsEditMessageModel.value.type = 'edit'
  wsEditMessageModel.value.editInfoModel.status = 'release'
  wsEditMessageModel.value.editInfoModel.cellId = cellId
  wsEditMessageModel.value.editInfoModel.cellName = ''
  wsEditMessageModel.value.editInfoModel.editorInfo.id = userStore.user.id as number
  wsEditMessageModel.value.editInfoModel.editorInfo.avatar = userStore.user.avatar || ''
  wsEditMessageModel.value.editInfoModel.editorInfo.name = userStore.user.username || ''
  ws.value.send(JSON.stringify(wsEditMessageModel.value))
}
// 初始化 WebSocket 连接
const initWebSocket = () => {
  const userId = userStore.user.id
  const tableId = route.params.id

  // 如果已经存在连接，先清理
  cleanupWebSocket()

  // 创建 WebSocket 连接
  const wsUrl = `${import.meta.env.VITE_APP_WS_BASE_URL}/api/ws/table/${tableId}/${userId}`

  try {
    ws.value = new WebSocket(wsUrl)
  } catch (error) {
    console.error('WebSocket 连接失败:', error)
    return
  }

  // 连接建立时的处理
  ws.value.onopen = () => {
    wsConnected.value = true
    reconnectCount.value = 0
    isReconnecting.value = false
    isNormalClosure.value = false
    startHeartbeat() // 开始心跳检测
  }

  // 接收消息的处理
  ws.value.onmessage = (event) => {
    const data = JSON.parse(event.data)
    // 判断是否是连接数据
    if (data.operation === 'open') {
      // 处理连接数据
      handleConnectData(data as CUSTOMAPI.ConnectDataModel)
      return
    }
    if (data.operation === 'close') {
      // 处理连接关闭
      handleCloseData(data as CUSTOMAPI.ConnectDataModel)
      return
    }
    //根据消息type:table / edit 转发到不同的函数中
    if (data.type === 'table') {
      // 处理表格返回
      const result = data as CUSTOMAPI.WsReturnModel
      handleTableMessage(result.tableReturn as CUSTOMAPI.TableReturnModel)
    }
    if (data.type == 'edit') {
      //处理编辑权
      const result = data as CUSTOMAPI.WsReturnModel
      handleEditMessage(result.editReturn as CUSTOMAPI.EditReturnModel)
    }
    if (data.type == 'init') {
      //处理初始化
      const result = data as CUSTOMAPI.WsReturnModel
      handleInitMessage(result.initEditStatus as Record<string, CUSTOMAPI.SimpleUserModel>)
    }
  }

  // 连接关闭的处理
  ws.value.onclose = (event) => {
    wsConnected.value = false
    stopHeartbeat() // 停止心跳检测
    console.log('连接已关闭')
    if (!isNormalClosure.value) {
      Notification.warning('WebSocket 连接已关闭')
      handleReconnect()
    } else {
    }
  }

  // 错误处理
  ws.value.onerror = (error) => {
    console.error('WebSocket 错误:', error)
    wsConnected.value = false
    handleReconnect()
  }
  // 处理连接成功返回消息
  const handleConnectData = (data: CUSTOMAPI.ConnectDataModel) => {
    connectUser.value = data.connectUser
    totalOnline.value = data.totalOnline
    onlineUserList.value = data.onlineUserList
  }
  //处理连接关闭
  const handleCloseData = (data: CUSTOMAPI.ConnectDataModel) => {
    totalOnline.value = data.totalOnline
    onlineUserList.value = data.onlineUserList
  }
  // 处理Table消息
  const handleTableMessage = async (result: CUSTOMAPI.TableReturnModel) => {
    //解锁对应单元格
    wsEditMessageModel.value.type = 'edit'
    wsEditMessageModel.value.editInfoModel.status = 'release'
    wsEditMessageModel.value.editInfoModel.cellId = result.cellId
    ws.value?.send(JSON.stringify(wsEditMessageModel.value))

    if (result.operation == 'init') {
      //重新获取数据
      await doTaskFilter(editStore.taskFilter)
    }
    if (result.operation == 'update') {
      //重新获取数据
      await doTaskFilter(editStore.taskFilter)
    }
  }
  //处理Edit消息
  const handleEditMessage = (result: CUSTOMAPI.EditReturnModel) => {
    editStore.handleEditResponse(result)
  }
  //处理初始化消息
  const handleInitMessage = (result: Record<string, CUSTOMAPI.SimpleUserModel>) => {
    editStore.handleInitResponse(result)
  }
}
// 清理 WebSocket 连接
const cleanupWebSocket = () => {
  if (ws.value) {
    isNormalClosure.value = true // 标记为正常关闭
    ws.value.close(1000)
    ws.value = null
  }
  stopHeartbeat()
  wsConnected.value = false
}

// 重连处理
const handleReconnect = () => {
  if (isReconnecting.value) return

  if (reconnectCount.value >= MAX_RECONNECT_COUNT) {
    Notification.error('WebSocket 连接失败，请刷新页面重试')
    cleanupWebSocket()
    return
  }

  isReconnecting.value = true
  console.warn(`尝试第 ${reconnectCount.value + 1} 次重连...`)

  setTimeout(() => {
    reconnectCount.value++
    initWebSocket()
  }, RECONNECT_INTERVAL)
}

// 心跳检测
const startHeartbeat = () => {
  stopHeartbeat() // 先清除可能存在的心跳定时器

  heartbeatTimer.value = window.setInterval(() => {
    if (!ws.value || ws.value.readyState !== WebSocket.OPEN) {
      console.warn('心跳检测：连接异常')
      wsConnected.value = false
      handleReconnect()
      return
    }
  }, HEARTBEAT_INTERVAL)
}

// 停止心跳检测
const stopHeartbeat = () => {
  if (heartbeatTimer.value) {
    clearInterval(heartbeatTimer.value)
    heartbeatTimer.value = null
  }
}

// 组件卸载时清理
onUnmounted(() => {
  cleanupWebSocket()
})

// 路由变化时关闭连接
onBeforeRouteLeave(() => {
  cleanupWebSocket()
})
//#endregion
// #region 任务管理 数据与函数
const getCurrentProject = async () => {
  try {
    const res: any = await getProjectUsingGet({
      id: props.proId
    })
    if (res.code === 0) {
      currentProject.value = res.data
      //初始化当前里程碑
      //存在已选择里程碑，更新
      if (currentMilestone.value) {
        currentMilestone.value =
          currentProject.value?.mileStoneVoList?.find(
            (milestone) => milestone.id === currentMilestone.value?.id
          ) || null
      }
      //不存在已选择里程碑，选择第一个
      if (res.data.mileStoneVoList.length > 0 && currentMilestone.value === null) {
        currentMilestone.value = res.data.mileStoneVoList[0] || null
        if (currentMilestone.value) {
          await getCurrentMileStoneTaskCount(currentMilestone.value?.id)
        }
      }
    } else {
      Message.error(res.msg || '获取项目信息失败')
    }
  } catch (error) {
    Message.error('获取项目信息失败')
  }
}
// 里程碑相关
const currentMilestone = ref<API.MileStoneVo | null>(null)
const currentMileStoneTaskCount: Ref<API.TaskCountVo> = ref({})
const getCurrentMileStoneTaskCount = async (mileId: number | undefined) => {
  if (mileId) {
    try {
      const res: any = await getTaskCountByMileIdUsingGet({ mileId })
      if (res.code == 0) {
        currentMileStoneTaskCount.value = res.data
      } else {
        currentMileStoneTaskCount.value = {}
      }
    } catch (e) {
      console.error('里程碑任务计数错误', e)
    }
  }
}
// 处理里程碑切换
const handleMilestoneChange = (mileId: number | null) => {
  if (mileId === 0) {
    currentMilestone.value = null
  } else {
    currentMilestone.value =
      currentProject.value?.mileStoneVoList?.find((milestone) => mileId === milestone.id) || null
  }
  console.log('切换里程碑:', currentMilestone.value)
}
// 任务筛选相关
watch(
  () => editStore.taskFilter,
  async (newVal: string) => {
    await doTaskFilter(newVal)
  }
)
// 任务筛选处理函数
const doTaskFilter = async (filter: string) => {
  const handleAllTask = async () => {
    await getCurrentProject()
  }
  const handleMyTask = async () => {
    await getCurrentProject()
    await nextTick()
    if (currentProject.value) {
      //处理项目移除非我的任务
      const taskList = currentProject.value.taskVoList || []
      const myTaskList = taskList.filter((task) => task.owner?.id === userStore.user.id)
      currentProject.value.taskVoList = myTaskList
      //处理里程碑下的任务
      if (currentProject.value.mileStoneVoList) {
        currentProject.value.mileStoneVoList = currentProject.value.mileStoneVoList.map(
          (milestone) => {
            // 只过滤里程碑下的任务
            const myMilestoneTasks =
              milestone.taskVoList?.filter((task) => task.owner?.id === userStore.user.id) || []
            return {
              ...milestone,
              taskVoList: myMilestoneTasks
            }
          }
        )
      }

      //处理迭代下的任务和需求下的任务
      if (currentProject.value.mileStoneVoList) {
        currentProject.value.mileStoneVoList = currentProject.value.mileStoneVoList.map(
          (milestone) => {
            if (milestone.iterationVoList) {
              // 过滤迭代列表
              milestone.iterationVoList = milestone.iterationVoList
                .map((iteration) => {
                  // 过滤迭代下的直接任务
                  const myIterationTasks =
                    iteration.taskVoList?.filter((task) => task.owner?.id === userStore.user.id) ||
                    []

                  // 处理需求及其任务
                  const requirementList = iteration.requirementVoList || []
                  const filteredRequirements = requirementList
                    .map((requirement) => {
                      // 过滤需求下的我的任务
                      const myRequirementTasks =
                        requirement.taskVoList?.filter(
                          (task) => task.owner?.id === userStore.user.id
                        ) || []

                      // 只有当需求下有我的任务时，才保留这个需求
                      if (myRequirementTasks.length > 0) {
                        return {
                          ...requirement,
                          taskVoList: myRequirementTasks
                        }
                      }
                      return null
                    })
                    .filter(Boolean) // 过滤掉返回 null 的需求

                  // 如果迭代下既没有我的任务，也没有包含我的任务的需求，则返回 null
                  if (myIterationTasks.length === 0 && filteredRequirements.length === 0) {
                    return null
                  }

                  return {
                    ...iteration,
                    taskVoList: myIterationTasks,
                    requirementVoList: filteredRequirements
                  }
                })
                .filter(Boolean) // 过滤掉返回 null 的迭代
            }
            return milestone
          }
        )
      }
      //处理完成后重新获取当前里程碑
      currentMilestone.value =
        currentProject.value?.mileStoneVoList?.find(
          (milestone) => milestone.id === currentMilestone.value?.id
        ) || null
    }
  }
  const handleOverdueTask = async () => {
    await getCurrentProject()
    await nextTick()
    if (currentProject.value) {
      const now = new Date()
      // 过滤项目直接任务
      currentProject.value.taskVoList = currentProject.value.taskVoList?.filter(
        (task) => task.status === 3 || (task.endTime && dayjs(task.endTime).toDate() < now)
      )

      // 过滤里程碑下的任务
      if (currentProject.value.mileStoneVoList) {
        currentProject.value.mileStoneVoList = currentProject.value.mileStoneVoList.map(
          (milestone) => ({
            ...milestone,
            taskVoList: milestone.taskVoList?.filter(
              (task) => task.status === 3 || (task.endTime && dayjs(task.endTime).toDate() < now)
            )
          })
        )
      }

      // 处理迭代下的任务和需求下的任务
      if (currentProject.value.mileStoneVoList) {
        currentProject.value.mileStoneVoList = currentProject.value.mileStoneVoList.map(
          (milestone) => {
            if (milestone.iterationVoList) {
              // 过滤迭代列表
              milestone.iterationVoList = milestone.iterationVoList
                .map((iteration) => {
                  // 过滤迭代下的直接任务
                  const overdueIterationTasks =
                    iteration.taskVoList?.filter(
                      (task) =>
                        task.status === 3 || (task.endTime && dayjs(task.endTime).toDate() < now)
                    ) || []

                  // 处理需求及其任务
                  const requirementList = iteration.requirementVoList || []
                  const filteredRequirements = requirementList
                    .map((requirement) => {
                      // 过滤需求下的逾期任务
                      const overdueRequirementTasks =
                        requirement.taskVoList?.filter(
                          (task) =>
                            task.status === 3 ||
                            (task.endTime && dayjs(task.endTime).toDate() < now)
                        ) || []

                      // 只有当需求下有逾期任务时，才保留这个需求
                      if (overdueRequirementTasks.length > 0) {
                        return {
                          ...requirement,
                          taskVoList: overdueRequirementTasks
                        }
                      }
                      return null
                    })
                    .filter(Boolean) // 过滤掉返回 null 的需求

                  // 如果迭代下既没有逾期任务，也没有包含逾期任务的需求，则返回 null
                  if (overdueIterationTasks.length === 0 && filteredRequirements.length === 0) {
                    return null
                  }

                  return {
                    ...iteration,
                    taskVoList: overdueIterationTasks,
                    requirementVoList: filteredRequirements
                  }
                })
                .filter(Boolean) // 过滤掉返回 null 的迭代
            }
            return milestone
          }
        )
      }

      // 处理完成后重新获取当前里程碑
      currentMilestone.value =
        currentProject.value?.mileStoneVoList?.find(
          (milestone) => milestone.id === currentMilestone.value?.id
        ) || null
    }
  }
  const handleTodayTask = async () => {
    await getCurrentProject()
    await nextTick()
    if (currentProject.value) {
      const now = new Date()
      // 过滤项目直接任务
      currentProject.value.taskVoList = currentProject.value.taskVoList?.filter((task) =>
        dayjs(task.endTime).isSame(now, 'day')
      )

      // 过滤里程碑下的任务
      if (currentProject.value.mileStoneVoList) {
        currentProject.value.mileStoneVoList = currentProject.value.mileStoneVoList.map(
          (milestone) => ({
            ...milestone,
            taskVoList: milestone.taskVoList?.filter((task) =>
              dayjs(task.endTime).isSame(now, 'day')
            )
          })
        )
      }

      // 处理迭代下的任务和需求下的任务
      if (currentProject.value.mileStoneVoList) {
        currentProject.value.mileStoneVoList = currentProject.value.mileStoneVoList.map(
          (milestone) => {
            if (milestone.iterationVoList) {
              // 过滤迭代
              milestone.iterationVoList = milestone.iterationVoList
                .filter(
                  (iteration) =>
                    // 保留今日到期的迭代或包含今日到期任务/需求的迭代
                    dayjs(iteration.endTime).isSame(now, 'day') ||
                    iteration.taskVoList?.some((task) => dayjs(task.endTime).isSame(now, 'day')) ||
                    iteration.requirementVoList?.some(
                      (req) =>
                        dayjs(req.endTime).isSame(now, 'day') ||
                        req.taskVoList?.some((task) => dayjs(task.endTime).isSame(now, 'day'))
                    )
                )
                .map((iteration) => {
                  // 过滤迭代下的直接任务
                  const todayIterationTasks =
                    iteration.taskVoList?.filter((task) =>
                      dayjs(task.endTime).isSame(now, 'day')
                    ) || []

                  // 处理需求及其任务
                  const requirementList = iteration.requirementVoList || []
                  const filteredRequirements = requirementList
                    .filter(
                      (requirement) =>
                        // 保留今日到期的需求或包含今日到期任务的需求
                        dayjs(requirement.endTime).isSame(now, 'day') ||
                        requirement.taskVoList?.some((task) =>
                          dayjs(task.endTime).isSame(now, 'day')
                        )
                    )
                    .map((requirement) => {
                      // 过滤需求下的今日到期任务
                      const todayRequirementTasks =
                        requirement.taskVoList?.filter((task) =>
                          dayjs(task.endTime).isSame(now, 'day')
                        ) || []

                      return {
                        ...requirement,
                        taskVoList: todayRequirementTasks
                      }
                    })

                  return {
                    ...iteration,
                    taskVoList: todayIterationTasks,
                    requirementVoList: filteredRequirements
                  }
                })
            }
            return milestone
          }
        )
      }

      // 处理完成后重新获取当前里程碑
      currentMilestone.value =
        currentProject.value?.mileStoneVoList?.find(
          (milestone) => milestone.id === currentMilestone.value?.id
        ) || null
    }
  }
  const handleWeekTask = async () => {
    await getCurrentProject()
    await nextTick()
    if (currentProject.value) {
      const now = new Date()
      // 过滤项目直接任务
      currentProject.value.taskVoList = currentProject.value.taskVoList?.filter((task) =>
        dayjs(task.endTime).isSame(dayjs(now), 'week')
      )

      // 过滤里程碑下的任务
      if (currentProject.value.mileStoneVoList) {
        currentProject.value.mileStoneVoList = currentProject.value.mileStoneVoList.map(
          (milestone) => ({
            ...milestone,
            taskVoList: milestone.taskVoList?.filter((task) =>
              dayjs(task.endTime).isSame(dayjs(now), 'week')
            )
          })
        )
      }

      // 处理迭代下的任务和需求下的任务
      if (currentProject.value.mileStoneVoList) {
        currentProject.value.mileStoneVoList = currentProject.value.mileStoneVoList.map(
          (milestone) => {
            if (milestone.iterationVoList) {
              // 过滤迭代
              milestone.iterationVoList = milestone.iterationVoList
                .filter(
                  (iteration) =>
                    // 保留本周到期的迭代或包含本周到期任务/需求的迭代
                    dayjs(iteration.endTime).isSame(dayjs(now), 'week') ||
                    iteration.taskVoList?.some((task) =>
                      dayjs(task.endTime).isSame(dayjs(now), 'week')
                    ) ||
                    iteration.requirementVoList?.some(
                      (req) =>
                        dayjs(req.endTime).isSame(dayjs(now), 'week') ||
                        req.taskVoList?.some((task) =>
                          dayjs(task.endTime).isSame(dayjs(now), 'week')
                        )
                    )
                )
                .map((iteration) => {
                  // 过滤迭代下的直接任务
                  const weekIterationTasks =
                    iteration.taskVoList?.filter((task) =>
                      dayjs(task.endTime).isSame(dayjs(now), 'week')
                    ) || []

                  // 处理需求及其任务
                  const requirementList = iteration.requirementVoList || []
                  const filteredRequirements = requirementList
                    .filter(
                      (requirement) =>
                        // 保留本周到期的需求或包含本周到期任务的需求
                        dayjs(requirement.endTime).isSame(dayjs(now), 'week') ||
                        requirement.taskVoList?.some((task) =>
                          dayjs(task.endTime).isSame(dayjs(now), 'week')
                        )
                    )
                    .map((requirement) => {
                      // 过滤需求下的本周到期任务
                      const weekRequirementTasks =
                        requirement.taskVoList?.filter((task) =>
                          dayjs(task.endTime).isSame(dayjs(now), 'week')
                        ) || []

                      return {
                        ...requirement,
                        taskVoList: weekRequirementTasks
                      }
                    })

                  return {
                    ...iteration,
                    taskVoList: weekIterationTasks,
                    requirementVoList: filteredRequirements
                  }
                })
            }
            return milestone
          }
        )
      }

      // 处理完成后重新获取当前里程碑
      currentMilestone.value =
        currentProject.value?.mileStoneVoList?.find(
          (milestone) => milestone.id === currentMilestone.value?.id
        ) || null
    }
  }
  switch (filter) {
    case 'all':
      editStore.taskFilter = 'all'
      await handleAllTask()
      break
    case 'my':
      editStore.taskFilter = 'my'
      await handleMyTask()
      break
    case 'overdue':
      editStore.taskFilter = 'overdue'
      await handleOverdueTask()
      break
    case 'today':
      editStore.taskFilter = 'today'
      await handleTodayTask()
      break
    case 'week':
      editStore.taskFilter = 'week'
      await handleWeekTask()
      break
  }
  editStore.taskFilter = filter
}
// #endregion

//#region 表格 相关
// 表格展开的行的key
const expandedKeys = ref<string[]>([])

// 表格选择配置
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true
})

// 表格相关数据
const columns = [
  {
    title: '标题',
    dataIndex: 'title',
    slotName: 'name',
    width: 120,
    fixed: 'left'
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status',
    width: 50,
    align: 'center'
  },
  {
    title: '负责人',
    dataIndex: 'owner',
    slotName: 'owner',
    width: 54,
    align: 'center'
  },
  {
    title: '开始时间',
    dataIndex: 'startTime',
    slotName: 'startTime',
    width: 54,
    align: 'center'
  },
  {
    title: '结束时间',
    dataIndex: 'endTime',
    slotName: 'endTime',
    width: 54,
    align: 'center'
  },
  {
    title: '完成时间',
    dataIndex: 'completeTime',
    slotName: 'completeTime',
    width: 54,
    align: 'center'
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    slotName: 'priority',
    width: 54,
    align: 'center'
  },
  {
    title: '附件数',
    dataIndex: 'attachCount',
    slotName: 'attachCount',
    width: 54,
    align: 'center'
  },
  {
    title: '进度',
    dataIndex: 'progress',
    slotName: 'progress',
    width: 54,
    align: 'center'
  },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operations',
    width: 54,
    align: 'center',
    fixed: 'right'
  }
]

// 表格数据转换函数
const transformTableData = (milestone: API.MileStoneVo) => {
  if (!milestone) return []

  const result: any = []

  // 添加里程碑直接任务
  if (milestone.taskVoList?.length) {
    result.push(
      ...milestone.taskVoList.map((task) => ({
        ...task,
        key: `task-${task.id}`,
        type: 'task',
        className: 'table-row-task'
      }))
    )
  }

  // 添加迭代及其任务
  if (milestone.iterationVoList?.length) {
    milestone.iterationVoList.forEach((iteration) => {
      // 添加迭代
      const iterationNode = {
        ...iteration,
        key: `iteration-${iteration.id}`,
        type: 'iteration',
        className: 'table-row-iteration',
        children: []
      }

      // 添加迭代下的直接任务
      if (iteration.taskVoList?.length) {
        iterationNode.children.push(
          ...iteration.taskVoList.map((task) => ({
            ...task,
            key: `iteration-task-${task.id}`,
            type: 'task',
            className: 'table-row-task'
          }))
        )
      }

      // 添加需求及其任务
      if (iteration.requirementVoList?.length) {
        iteration.requirementVoList.forEach((requirement) => {
          const reqNode = {
            ...requirement,
            key: `requirement-${requirement.id}`,
            type: 'requirement',
            className: 'table-row-requirement',
            children:
              requirement.taskVoList?.map((task) => ({
                ...task,
                key: `requirement-task-${task.id}`,
                type: 'task',
                className: 'table-row-task'
              })) || []
          }
          iterationNode.children.push(reqNode)
        })
      }

      result.push(iterationNode)
    })
  }

  return result
}
// 项目下直接任务函数
const transformProjectTaskData = () => {
  return (
    currentProject.value?.taskVoList?.map((task) => ({
      ...task,
      key: `task-${task.id}`,
      type: 'task',
      className: 'table-row-task'
    })) || []
  )
}
//表格数据采用计算属性
const tableData = computed(() => {
  if (currentMilestone.value) {
    return transformTableData(currentMilestone.value)
  } else {
    //表格数据采用项目下直接任务
    return transformProjectTaskData()
  }
})

// 获取类型图标组件
const getTypeIcon = (type: string) => {
  switch (type) {
    case 'task':
      return IconFile
    case 'iteration':
      return IconCalendar
    case 'requirement':
      return IconBook
    default:
      return IconFile
  }
}
//#endregion
// 获取所有可展开节点的keys
const getAllExpandableKeys = (data: any[]) => {
  const keys: string[] = []
  const traverse = (items: any[]) => {
    items.forEach((item) => {
      if (item.children?.length) {
        keys.push(item.key)
        traverse(item.children)
      }
    })
  }
  traverse(data)
  return keys
}

// 添加编辑状态管理
const editingKey = ref<string | null>(null)
const editingField = ref('')
const editingValues = ref({
  title: '',
  status: '',
  priority: '',
  ownerId: '',
  startTime: '',
  endTime: '',
  completeTime: ''
})

// 生成唯一的单元格ID
const generateCellId = (record: any, field?: string) => {
  if (!field) {
    return `${record.type}-${record.id}` //代表锁定行 例如: task-123
  }
  return `${record.type}-${record.id}-${field}` // 例如: task-123-title
}
/**
 * 通用单元格编辑处理函数
 * @param record 记录数据
 * @param field 字段名称 (如: 'title', 'status', 'priority' 等)
 */

// 修改编辑按钮的显示条件
const isEditable = (record: any, field?: string) => {
  const rowId = generateCellId(record)
  const cellId = generateCellId(record, field)

  // 获取当前单元格的编辑状态
  const cellEditInfo = editStore.editingCells.get(cellId)

  // 如果是当前用户正在编辑的单元格，应该允许编辑
  if (cellEditInfo && cellEditInfo.editorInfo.id === userStore.user.id) {
    return true
  }

  // 如果行被锁定，或单元格被其他用户锁定，不允许编辑
  return !editStore.editingRows.has(rowId) && !editStore.editingCells.get(cellId)
}
const handleCellEdit = async (record: any, field: string) => {
  const rowId = generateCellId(record) // 获取行ID
  // 检查行是否被锁定
  const rowLockInfo = editStore.editingRows.get(rowId)
  if (rowLockInfo) {
    Message.warning(`${rowLockInfo.editorInfo.name} 正在编辑此内容`)
    return
  }

  const cellId = generateCellId(record, field)
  const checkResult = editStore.checkCellEditable(cellId)

  if (checkResult === true) {
    // 申请单元格
    handleApplyCell(cellId)
    // 等待获取编辑权结果
    const editReturn = (await editStore.requestEditPermission(cellId)) as CUSTOMAPI.EditReturnModel
    // 获取到编辑权
    if (editReturn.result === EDIT_STATUS.EDITING) {
      editingKey.value = record.key
      editingField.value = field // 记录当前编辑的字段

      // 根据不同字段类型设置编辑值
      switch (field) {
        case 'title':
          editingValues.value.title = record.title
          break
        case 'status':
          editingValues.value.status = record.status.toString()
          break
        case 'priority':
          editingValues.value.priority = record.priority.toString()
          break
        case 'ownerId':
          editingValues.value.ownerId = record.owner?.id.toString()
          break
        case 'completeTime':
          editingValues.value.completeTime = record.completeTime
            ? record.completeTime.toString()
            : ''
          break
        default:
          editingValues.value[field] = record[field]?.toString() || ''
      }
    } else {
      // 获取编辑权失败
      Message.warning(`${editReturn.editInfo.editorInfo.name} 正在编辑此内容`)
    }
  } else {
    // 显示提示信息
    Message.warning(`${checkResult.editor.editorInfo.name} 正在编辑此内容`)
  }
}

// 保存处理函数
const handleSave = async (record: any, field: string, value: string) => {
  // 添加防重复提交标记
  if (editingKey.value === null) {
    return
  }

  if (editingValues.value[field].trim() === '' || !ws.value) {
    return
  }

  // 先清空编辑状态，防止重复触发
  editingKey.value = null
  editingField.value = ''
  editingValues.value = {
    title: '',
    status: '',
    priority: '',
    ownerId: '',
    startTime: '',
    endTime: ''
  }
  if (record.type === 'task') {
    await handleSaveTask(record, field, value)
  }
  if (record.type === 'requirement') {
    await handleSaveRequirement(record, field, value)
  }
  if (record.type === 'iteration') {
    await handleSaveIteration(record, field, value)
  }
}
//#region 保存任务

const updateTaskRequet: Ref<API.UpdateTaskRequest> = ref({})
const handleSaveTask = async (record: any, field: string, value: string) => {
  //-1代表不修改
  updateTaskRequet.value.id = record.id
  updateTaskRequet.value.mileId = -1
  updateTaskRequet.value.iterId = -1
  updateTaskRequet.value.reqId = -1
  if (field === 'title') {
    updateTaskRequet.value.title = value
  }
  if (field === 'status') {
    updateTaskRequet.value.status = Number(value)
  }
  if (field === 'ownerId') {
    updateTaskRequet.value.ownerId = Number(value)
  }
  if (field === 'priority') {
    updateTaskRequet.value.priority = Number(value)
  }
  if (field === 'startTime') {
    if (dayjs(value).isAfter(dayjs(record.endTime))) {
      handleCancel(generateCellId(record, 'startTime'))
      Message.error('开始时间不能晚于结束时间')
      return
    }
    updateTaskRequet.value.startTime = dayjs(value).format('YYYY-MM-DDTHH:mm:ss')
  }
  if (field === 'endTime') {
    if (dayjs(value).isBefore(dayjs(record.startTime))) {
      handleCancel(generateCellId(record, 'endTime'))
      Message.error('结束时间不能早于开始时间')
      return
    }
    updateTaskRequet.value.endTime = dayjs(value).format('YYYY-MM-DDTHH:mm:ss')
  }
  try {
    // 发送表格编辑消息
    wsTableMessageModel.value.type = 'table'
    wsTableMessageModel.value.tableMessageModel.cellId = generateCellId(record, field)
    wsTableMessageModel.value.tableMessageModel.operation = 'update'
    wsTableMessageModel.value.tableMessageModel.sendTime = dayjs().format('YYYY-MM-DDTHH:mm:ss')
    wsTableMessageModel.value.tableMessageModel.sendId = userStore.user.id as number
    wsTableMessageModel.value.tableMessageModel.type = 3
    wsTableMessageModel.value.tableMessageModel.updateTaskRequest = updateTaskRequet.value
    ws.value?.send(JSON.stringify(wsTableMessageModel.value))
  } catch (error) {
    Message.error('保存任务失败' + error)
  }
}
// #endregion
//#region 保存需求
const updateRequirementRequet: Ref<API.UpdateRequirementRequest> = ref({})
const handleSaveRequirement = async (record: any, field: string, value: string) => {
  console.log('保存需求', {
    record,
    field,
    value
  })
  //-1代表不修改
  updateRequirementRequet.value.id = record.id
  updateRequirementRequet.value.mileId = -1
  updateRequirementRequet.value.iterId = -1
  if (field === 'title') {
    updateRequirementRequet.value.title = value
  }
  if (field === 'status') {
    updateRequirementRequet.value.status = Number(value)
  }
  if (field === 'ownerId') {
    updateRequirementRequet.value.ownerId = Number(value)
  }
  if (field === 'priority') {
    updateRequirementRequet.value.priority = Number(value)
  }
  try {
    // 发送表格编辑消息
    wsTableMessageModel.value.type = 'table'
    wsTableMessageModel.value.tableMessageModel.cellId = generateCellId(record, field)
    wsTableMessageModel.value.tableMessageModel.operation = 'update'
    wsTableMessageModel.value.tableMessageModel.sendTime = dayjs().format('YYYY-MM-DDTHH:mm:ss')
    wsTableMessageModel.value.tableMessageModel.sendId = userStore.user.id as number
    wsTableMessageModel.value.tableMessageModel.type = 2
    wsTableMessageModel.value.tableMessageModel.updateRequirementRequest =
      updateRequirementRequet.value
    ws.value?.send(JSON.stringify(wsTableMessageModel.value))
  } catch (error) {
    Message.error('保存需求失败' + error)
  }
}
// #endregion
//#region 保存迭代
const updateIterationRequet: Ref<API.UpdateIterationRequest> = ref({})
const handleSaveIteration = async (record: any, field: string, value: string) => {
  console.log('保存迭代', {
    record,
    field,
    value
  })
  //-1代表不修改
  updateIterationRequet.value.id = record.id
  updateIterationRequet.value.mileId = -1
  if (field === 'title') {
    updateIterationRequet.value.title = value
  }
  try {
    // 发送表格编辑消息
    wsTableMessageModel.value.type = 'table'
    wsTableMessageModel.value.tableMessageModel.cellId = generateCellId(record, field)
    wsTableMessageModel.value.tableMessageModel.operation = 'update'
    wsTableMessageModel.value.tableMessageModel.sendTime = dayjs().format('YYYY-MM-DDTHH:mm:ss')
    wsTableMessageModel.value.tableMessageModel.sendId = userStore.user.id as number
    wsTableMessageModel.value.tableMessageModel.type = 1
    wsTableMessageModel.value.tableMessageModel.updateIterationRequest = updateIterationRequet.value
    ws.value?.send(JSON.stringify(wsTableMessageModel.value))
  } catch (error) {
    Message.error('保存迭代失败' + error)
  }
}
// #endregion
// 取消编辑
const handleCancel = (cellId: string) => {
  handleReleaseCell(cellId)
  editingKey.value = null
  editingField.value = ''
  editingValues.value = {
    title: '',
    status: '',
    priority: '',
    ownerId: '',
    startTime: '',
    endTime: ''
  }
}

// 添加自动聚焦指令
const vFocus = {
  mounted: (el: HTMLElement) => {
    nextTick(() => {
      el.querySelector('input')?.focus()
    })
  }
}
//#region 初始化
const initData = async () => {
  if (!userStore.user.id) {
    Message.error('请先登录')
    return
  }
  await getCurrentProject()
  await getProjectMembers()
  if (!ws.value) {
    initWebSocket()
  }
  // 设置默认展开所有节点
  if (tableData.value) {
    expandedKeys.value = getAllExpandableKeys(tableData.value)
  }
}

onMounted(async () => {
  await initData()
})
// #endregion

// 监听 tableData 变化，保持展开状态
watch(tableData, (newData) => {
  if (newData) {
    expandedKeys.value = getAllExpandableKeys(newData)
  }
})

// 获取时间范围
const getTimeRange = (record: any) => {
  // 如果是需求
  if (record.type === 'requirement') {
    // 遍历查找对应的迭代
    for (const iteration of currentMilestone.value?.iterationVoList || []) {
      if (iteration.requirementVoList?.some((req) => req.id === record.id)) {
        return {
          startTime: record.startTime, // 使用需求自己的开始时间
          endTime: iteration.endTime // 使用迭代的结束时间作为最晚时间
        }
      }
    }
  }
  // 如果是迭代
  else if (record.type === 'iteration') {
    // 获取所属里程碑的时间范围
    if (currentMilestone.value) {
      return {
        startTime: currentMilestone.value.startTime, // 使用里程碑的开始时间作为最早时间
        endTime: currentMilestone.value.endTime // 使用里程碑的结束时间作为最晚时间
      }
    }
  }
  // 如果是任务类型，按照优先级判断所属关系
  else if (record.type === 'task') {
    // 1. 需求下的任务（优先判断）
    if (record.reqId) {
      // 遍历查找对应的需求
      for (const iteration of currentMilestone.value?.iterationVoList || []) {
        for (const req of iteration.requirementVoList || []) {
          if (req.id === record.reqId) {
            return {
              startTime: req.startTime, // 使用需求的开始时间
              endTime: req.endTime // 使用需求的结束时间
            }
          }
        }
      }
    }
    // 2. 迭代下的任务（其次判断）
    else if (record.iterId) {
      for (const iteration of currentMilestone.value?.iterationVoList || []) {
        if (iteration.id === record.iterId) {
          return {
            startTime: iteration.startTime,
            endTime: iteration.endTime
          }
        }
      }
    }
    // 3. 里程碑下的任务（再次判断）
    else if (record.mileId) {
      if (currentMilestone.value?.id === record.mileId) {
        return {
          startTime: currentMilestone.value.startTime, // 里程碑开始时间作为最早时间
          endTime: currentMilestone.value.endTime // 使用里程碑的结束时间
        }
      }
    }
    // 4. 项目直接任务（最后判断）
    else if (record.proId) {
      return {
        startTime: currentProject.value?.startTime, // 使用项目的开始时间
        endTime: currentProject.value?.endTime // 使用项目的结束时间
      }
    }
  }
  return null
}

// 判断开始时间是否禁用
const isStartTimeDisabled = (current: Date | null, record: any) => {
  if (!current) return false

  const currentDate = dayjs(current)
  const timeRange = getTimeRange(record)

  if (timeRange) {
    const rangeStartTime = dayjs(timeRange.startTime).startOf('day')
    const rangeEndTime = dayjs(timeRange.endTime).endOf('day')
    const taskEndTime = record.endTime ? dayjs(record.endTime) : null

    // 检查日期是否在范围内
    if (currentDate.isBefore(rangeStartTime) || currentDate.isAfter(rangeEndTime)) {
      return true
    }

    // 如果有结束时间，开始时间不能晚于结束时间
    if (taskEndTime && currentDate.isAfter(taskEndTime)) {
      return true
    }
  }

  return false
}

// 判断结束时间是否禁用
const isEndTimeDisabled = (current: Date | null, record: any) => {
  if (!current) return false

  const currentDate = dayjs(current)
  const timeRange = getTimeRange(record)

  if (timeRange) {
    // 如果是任务类型
    if (record.type === 'task') {
      const rangeStartTime = dayjs(timeRange.startTime)
      const rangeEndTime = dayjs(timeRange.endTime)
      // 检查日期是否在范围内
      if (
        currentDate.startOf('day').isBefore(rangeStartTime.startOf('day')) ||
        currentDate.endOf('day').isAfter(rangeEndTime.endOf('day'))
      ) {
        return true
      }

      return false
    }
    // 如果是需求
    else if (record.type === 'requirement') {
      const rangeStartTime = dayjs(timeRange.startTime)
      const rangeEndTime = dayjs(timeRange.endTime)

      // 检查日期是否在范围内
      if (
        currentDate.startOf('day').isBefore(rangeStartTime.startOf('day')) ||
        currentDate.endOf('day').isAfter(rangeEndTime.endOf('day'))
      ) {
        return true
      }

      return false
    }
    // 其他类型记录的处理（迭代等）
    else if (record.type === 'iteration') {
      const rangeStartTime = dayjs(timeRange.startTime)
      const rangeEndTime = dayjs(timeRange.endTime)
      // 检查日期是否在范围内
      if (
        currentDate.startOf('day').isBefore(rangeStartTime.startOf('day')) ||
        currentDate.endOf('day').isAfter(rangeEndTime.endOf('day'))
      ) {
        return true
      }
    }
  }

  return false
}

// 判断完成时间是否禁用
const isCompleteTimeDisabled = (current: Date | null, record: any) => {
  if (!current) return false

  const currentDate = dayjs(current)

  // 如果没有结束时间，不能选择完成时间
  if (!record.endTime) {
    return true
  }

  const endTime = dayjs(record.endTime)

  // 完成时间不能早于结束时间
  if (currentDate.isBefore(endTime)) {
    return true
  }

  return false
}

const previewWrapper = ref({
  taskPreviewVisiable: false,
  iterationPreviewVisiable: false,
  requirementPreviewVisiable: false,
  taskPreviewId: null,
  iterationPreviewId: null,
  requirementPreviewId: null
})
// 编辑视窗
const handleEdit = (record: any) => {
  // 生成行号 (只包含一个 '-' 的标识符)
  const rowKey = generateCellId(record)
  console.log('编辑行号:', rowKey)

  // 检查行是否可编辑
  const checkResult = editStore.checkCellEditable(rowKey)

  if (checkResult === true) {
    // 申请单元格
    handleApplyCell(rowKey)
    // 等待获取编辑权结果
    editStore.requestEditPermission(rowKey).then((editReturn: CUSTOMAPI.EditReturnModel) => {
      if (editReturn.result === EDIT_STATUS.EDITING) {
        // 编辑权限获取成功，继续处理
        switch (record?.type) {
          case 'task':
            previewWrapper.value.taskPreviewVisiable = true
            previewWrapper.value.taskPreviewId = record.id
            break
          case 'requirement':
            previewWrapper.value.requirementPreviewVisiable = true
            previewWrapper.value.requirementPreviewId = record.id
            break
          case 'iteration':
            previewWrapper.value.iterationPreviewVisiable = true
            previewWrapper.value.iterationPreviewId = record.id
            break
        }
      } else {
        // 编辑权限获取失败
        Message.warning(`${editReturn.editInfo.editorInfo.name} 正在编辑此内容`)
      }
    })
  } else {
    // 显示提示信息
    Message.warning(`${checkResult.editor.editorInfo.name} 正在编辑此内容`)
  }
}

// 删除确认
const handleDelete = async (record: any) => {
  switch (record.type) {
    case 'task':
      const res: any = await deleteTaskUsingDelete({ taskId: record.id })
      if (res.code === 0) {
        await doInitForAll()
      }
      break
  }
}
//创建任务
const taskCreateVisible = ref(false)
const handleCreateTask = () => {
  taskCreateVisible.value = true
}
// 创建需求
const requirementCreateVisible = ref(false)
const handleCreateRequirement = () => {
  requirementCreateVisible.value = true
}
// 创建迭代
const iterationCreateVisible = ref(false)
const handleCreateIteration = () => {
  iterationCreateVisible.value = true
}
// 创建里程碑
const milestoneCreateVisible = ref(false)
const handleCreateMilestone = () => {
  milestoneCreateVisible.value = true
}

//同时所有人重新加载
const doInitForAll = async () => {
  wsTableMessageModel.value.type = 'table'
  wsTableMessageModel.value.tableMessageModel.operation = 'init'
  wsTableMessageModel.value.tableMessageModel.sendTime = dayjs().format('YYYY-MM-DDTHH:mm:ss')
  wsTableMessageModel.value.tableMessageModel.sendId = userStore.user.id as number
  ws.value?.send(JSON.stringify(wsTableMessageModel.value))
}

const handleEditClose = async (id: number, type: string) => {
  //释放行
  let row
  switch (type) {
    case 'task':
      row = `${type}-${id}`
      break
    case 'requirement':
      row = `${type}-${id}`
      break
    case 'iteration':
      row = `${type}-${id}`
      break
  }
  if (row) {
    handleReleaseCell(row)
    //全体重新获取数据
    await doInitForAll()
  }
}
</script>

<template>
  <a-card class="tasks-container">
    <!-- 顶部工具栏 -->
    <template #title>
      <div class="header-section">
        <!-- 左侧搜索和筛选 -->
        <div class="left-section">
          <a-input-search
            placeholder="搜索任务"
            style="width: 200px; margin-right: 16px"
            allow-clear
          />
          <a-space>
            <a-radio-group type="button" v-model="editStore.taskFilter">
              <a-radio value="all">全部任务</a-radio>
              <a-radio value="my">我负责的任务</a-radio>
              <a-radio value="overdue">已逾期的任务</a-radio>
              <a-radio value="today">今日到期</a-radio>
              <a-radio value="week">本周到期</a-radio>
            </a-radio-group>
          </a-space>
        </div>

        <!-- 右侧在线用户展示 -->
        <div class="online-users-section">
          <a-space align="center">
            <a-space align="center" size="mini">
              <icon-user />
              <span>{{ totalOnline }}</span>
            </a-space>

            <a-popover position="br">
              <div class="avatar-group">
                <template v-if="onlineUserList.length <= 3">
                  <a-avatar
                    v-for="user in onlineUserList"
                    :key="user.id"
                    :size="28"
                    :image-url="user.avatar"
                  >
                    {{ user.name?.[0] }}
                  </a-avatar>
                </template>
                <template v-else>
                  <div class="overlapped-avatars">
                    <a-avatar
                      v-for="(user, index) in onlineUserList.slice(0, 8)"
                      :key="user.id"
                      :size="28"
                      :style="{ marginLeft: index > 0 ? '-20%' : '0' }"
                      :image-url="user.avatar"
                    >
                      {{ user.name?.[0] }}
                    </a-avatar>
                    <span v-if="onlineUserList.length > 8" class="more-users">...</span>
                  </div>
                </template>
              </div>

              <!-- 悬浮显示的用户列表 -->
              <template #content>
                <div class="online-users-list">
                  <div v-for="user in onlineUserList" :key="user.id" class="user-item">
                    <a-avatar :size="24" :image-url="user.avatar">
                      {{ user.name?.[0] }}
                    </a-avatar>
                    <span>{{ user.name }}</span>
                  </div>
                </div>
              </template>
            </a-popover>
          </a-space>
        </div>
      </div>
    </template>

    <!-- 右上角操作按钮 -->
    <template #extra>
      <a-dropdown>
        <a-button type="primary">
          + 新建
          <icon-down />
        </a-button>
        <template #content>
          <a-doption @click="handleCreateMilestone">新建里程碑</a-doption>
          <a-doption @click="handleCreateIteration">新建迭代</a-doption>
          <a-doption @click="handleCreateRequirement">新建需求</a-doption>
          <a-doption @click="handleCreateTask">新建任务</a-doption>
        </template>
      </a-dropdown>
    </template>

    <!-- 主体内容区 -->
    <div class="tasks-content">
      <div class="table-section">
        <a-table
          :columns="columns"
          :data="tableData"
          :pagination="false"
          v-model:expanded-keys="expandedKeys"
          :row-selection="rowSelection"
          :scroll="{
            x: 2000,
            y: '100%'
          }"
          :scrollBar="true"
          :defaultExpandAllRows="true"
          size="mini"
          bordered
          stripe
        >
          <!-- 标题列 -->
          <template #name="{ record }">
            <div class="title-cell">
              <!-- 编辑状态 -->
              <template v-if="editingKey === record.key && editingField === 'title'">
                <a-input
                  v-model="editingValues.title"
                  :default-value="record.title"
                  class="edit-input"
                  @blur="handleSave(record, 'title', editingValues.title)"
                  @keydown.enter.prevent="handleSave(record, 'title', editingValues.title)"
                  @press-esc="handleCancel"
                  v-focus
                />
              </template>
              <!-- 非编辑状态 -->
              <template v-else>
                <div class="title-content">
                  <!-- 左侧图标和标题 -->
                  <div class="title-left">
                    <component :is="getTypeIcon(record.type)" />
                    <span
                      :style="{
                        color:
                          record.type === 'task' ? 'var(--color-text-1)' : 'var(--color-text-2)',
                        fontWeight: record.type !== 'task' ? 500 : 400
                      }"
                    >
                      <span class="type-prefix" :class="record.type">
                        <template v-if="record.type === 'iteration'">【迭代】</template>
                        <template v-else-if="record.type === 'requirement'">【需求】</template>
                        <template v-else-if="record.type === 'task'">【任务】</template>
                      </span>
                      {{ record.title }}
                    </span>
                  </div>
                  <!-- 上方编辑状态指示器 -->
                  <EditIndicator :cellId="generateCellId(record, 'title')" />
                </div>

                <!-- 编辑按钮 -->
                <div v-if="isEditable(record, 'title')" class="edit-button">
                  <a-button type="text" size="mini" @click.stop="handleCellEdit(record, 'title')">
                    <icon-edit />
                  </a-button>
                </div>
              </template>
            </div>
          </template>

          <!-- 状态列 -->
          <template #status="{ record }">
            <div class="status-cell">
              <EditIndicator :cellId="generateCellId(record, 'status')" />
              <a-tag :color="getCompleteColor(record.status)">
                {{ getCompleteStatus(record.status) }}
              </a-tag>

              <!-- 使用 Popover 包装状态选择 -->
              <a-popover
                position="br"
                trigger="manual"
                :popup-visible="editingKey === record.key && editingField === 'status'"
                @popup-visible-change="
                  (visible) => !visible && handleCancel(generateCellId(record, 'status'))
                "
              >
                <template #content>
                  <div class="status-options">
                    <a-space direction="vertical" size="mini">
                      <a-button
                        v-for="status in Object.values(COMPLETE_STATUS_CONFIG).filter(
                          (s) => s.value !== 3 && s.value !== record.status
                        )"
                        :key="status.value"
                        type="text"
                        block
                        @click="handleSave(record, 'status', status.value.toString())"
                      >
                        <a-tag :color="status.color">{{ status.label }}</a-tag>
                      </a-button>
                    </a-space>
                  </div>
                </template>
                <!-- 触发器部分 -->
                <div
                  class="dropdown-trigger"
                  v-if="isEditable(record, 'status')"
                  @click.stop="handleCellEdit(record, 'status')"
                >
                  <a-button type="text" size="mini">
                    <icon-down />
                  </a-button>
                </div>
              </a-popover>
            </div>
          </template>

          <!-- 负责人列 -->
          <template #owner="{ record }">
            <div class="owner-cell">
              <EditIndicator :cellId="generateCellId(record, 'ownerId')" />
              <a-space align="center" justify="center" style="width: 100%; gap: 2px">
                <a-avatar v-if="record.owner" :size="24" :image-url="record.owner?.avatar">
                  {{ record.owner?.name?.[0] }}
                </a-avatar>
                <span v-if="record.owner">{{ record.owner?.name }}</span>
              </a-space>

              <!-- 使用 Popover 包装成员选择 -->
              <a-popover
                position="br"
                trigger="manual"
                :popup-visible="editingKey === record.key && editingField === 'ownerId'"
                @popup-visible-change="
                  (visible) => !visible && handleCancel(generateCellId(record, 'ownerId'))
                "
              >
                <template #content>
                  <div class="member-options">
                    <a-space direction="vertical" size="mini">
                      <a-button
                        v-for="member in projectMembers"
                        :key="member.id"
                        type="text"
                        block
                        :disabled="member.id === record.ownerId"
                        @click="handleSave(record, 'ownerId', member?.id.toString())"
                      >
                        <a-space>
                          <a-avatar :size="24" :image-url="member.avatar">
                            {{ member.name?.[0] }}
                          </a-avatar>
                          <span>{{ member.name }}</span>
                        </a-space>
                      </a-button>
                    </a-space>
                  </div>
                </template>
                <!-- 触发器部分 -->
                <div
                  class="dropdown-trigger"
                  v-if="isEditable(record, 'ownerId')"
                  @click.stop="handleCellEdit(record, 'ownerId')"
                >
                  <a-button type="text" size="mini">
                    <icon-down />
                  </a-button>
                </div>
              </a-popover>
            </div>
          </template>
          <!-- 开始时间列 -->
          <template #startTime="{ record }">
            <div class="time-cell">
              <EditIndicator :cellId="generateCellId(record, 'startTime')" />
              <span>{{ dayjs(record.startTime).format('YYYY-MM-DD HH:mm') }}</span>

              <!-- 使用 Popover 包装时间选择器 -->
              <a-popover
                position="br"
                trigger="manual"
                :popup-visible="editingKey === record.key && editingField === 'startTime'"
                @popup-visible-change="
                  (visible) => !visible && handleCancel(generateCellId(record, 'startTime'))
                "
              >
                <template #content>
                  <div class="date-picker-container">
                    <a-date-picker
                      show-time
                      placeholder="选择开始时间"
                      hide-trigger
                      :default-value="record.startTime"
                      :disabled-date="(current) => isStartTimeDisabled(current, record)"
                      @ok="
                        (startTime) =>
                          handleSave(
                            record,
                            'startTime',
                            dayjs(startTime).format('YYYY-MM-DDTHH:mm')
                          )
                      "
                    />
                  </div>
                </template>
                <!-- 触发器部分 -->
                <div
                  class="dropdown-trigger"
                  v-if="isEditable(record, 'startTime')"
                  @click.stop="handleCellEdit(record, 'startTime')"
                >
                  <a-button type="text" size="mini">
                    <icon-down />
                  </a-button>
                </div>
              </a-popover>
            </div>
          </template>
          <!-- 结束时间列 -->
          <template #endTime="{ record }">
            <div class="time-cell">
              <EditIndicator :cellId="generateCellId(record, 'endTime')" />
              <span>{{ dayjs(record.endTime).format('YYYY-MM-DD HH:mm') }}</span>

              <!-- 使用 Popover 包装时间选择器 -->
              <a-popover
                position="br"
                trigger="manual"
                :popup-visible="editingKey === record.key && editingField === 'endTime'"
                @popup-visible-change="
                  (visible) => !visible && handleCancel(generateCellId(record, 'endTime'))
                "
              >
                <template #content>
                  <div class="date-picker-container">
                    <a-date-picker
                      show-time
                      placeholder="选择结束时间"
                      hide-trigger
                      :default-value="record.endTime"
                      :disabled-date="(current) => isEndTimeDisabled(current, record)"
                      @ok="
                        (endTime) =>
                          handleSave(record, 'endTime', dayjs(endTime).format('YYYY-MM-DDTHH:mm'))
                      "
                    />
                  </div>
                </template>
                <!-- 触发器部分 -->
                <div
                  class="dropdown-trigger"
                  v-if="isEditable(record, 'endTime')"
                  @click.stop="handleCellEdit(record, 'endTime')"
                >
                  <a-button type="text" size="mini">
                    <icon-down />
                  </a-button>
                </div>
              </a-popover>
            </div>
          </template>
          <!-- 完成时间列 -->
          <template #completeTime="{ record }">
            <div class="time-cell">
              <span>{{
                record.completeTime ? dayjs(record.completeTime).format('YYYY-MM-DD HH:mm') : '-'
              }}</span>
            </div>
          </template>
          <!-- 进度条列 -->
          <template #progress="{ record }">
            <a-progress
              v-if="record.progress !== undefined"
              :percent="record.progress"
              :stroke-width="4"
              size="small"
            />
          </template>
          <!-- 优先级列 -->
          <template #priority="{ record }">
            <template v-if="record.type === 'task' || record.type === 'requirement'">
              <div class="priority-cell">
                <EditIndicator :cellId="generateCellId(record, 'priority')" />
                <a-tag
                  :color="getTaskPriorityColor(record.priority)"
                  size="medium"
                  style="min-width: 48px; justify-content: center"
                >
                  {{ getPriorityLabel(record.priority) }}
                </a-tag>

                <!-- 使用 Popover 包装优先级选择 -->
                <a-popover
                  position="br"
                  trigger="manual"
                  :popup-visible="editingKey === record.key && editingField === 'priority'"
                  @popup-visible-change="
                    (visible) => !visible && handleCancel(generateCellId(record, 'priority'))
                  "
                >
                  <template #content>
                    <div class="priority-options">
                      <a-space direction="vertical" size="mini">
                        <a-button
                          v-for="priority in Object.values(PRIORITY_CONFIG)"
                          :key="priority.value"
                          type="text"
                          block
                          :disabled="priority.value === record.priority"
                          @click="handleSave(record, 'priority', priority.value.toString())"
                        >
                          <a-tag :color="priority.color">{{ priority.label }}</a-tag>
                        </a-button>
                      </a-space>
                    </div>
                  </template>
                  <!-- 触发器部分 -->
                  <div
                    class="dropdown-trigger"
                    v-if="isEditable(record, 'priority')"
                    @click.stop="handleCellEdit(record, 'priority')"
                  >
                    <a-button type="text" size="mini">
                      <icon-down />
                    </a-button>
                  </div>
                </a-popover>
              </div>
            </template>
          </template>
          <!-- 操作列 -->
          <template #operations="{ record }">
            <div class="operations-cell">
              <a-space>
                <a-button
                  type="text"
                  size="mini"
                  v-if="isEditable(record)"
                  @click="handleEdit(record)"
                >
                  <template #icon>
                    <icon-edit />
                  </template>
                </a-button>
                <a-button
                  type="text"
                  size="mini"
                  status="danger"
                  v-if="isEditable(record)"
                  @click="handleDelete(record)"
                >
                  <template #icon>
                    <icon-delete />
                  </template>
                </a-button>
              </a-space>
            </div>
          </template>
        </a-table>
      </div>
    </div>
    <!-- 底部工具栏 -->
    <div class="table-footer">
      <a-space>
        <a-button
          v-for="milestone in currentProject?.mileStoneVoList"
          :key="milestone.id"
          type="text"
          :class="{ 'milestone-btn': true, active: currentMilestone?.id === milestone.id }"
          @click="handleMilestoneChange(Number(milestone.id))"
        >
          {{ milestone.title }}
        </a-button>
        <a-button
          v-if="currentProject?.taskVoList?.length > 0"
          type="text"
          @click="handleMilestoneChange(0)"
        >
          项目任务
        </a-button>
      </a-space>
      <!-- 简化的统计信息 -->
      <div class="total-info">共 {{ currentMileStoneTaskCount?.totalTask }} 个</div>
    </div>
  </a-card>

  <!-- 任务弹窗 -->
  <TaskView
    v-if="previewWrapper.taskPreviewVisiable"
    :visible="previewWrapper.taskPreviewVisiable"
    :taskId="Number(previewWrapper.taskPreviewId)"
    @update:visible="(val) => (previewWrapper.taskPreviewVisiable = val)"
    @close="(val) => handleEditClose(val, 'task')"
  />
  <!-- 需求视图弹窗 -->
  <RequirementView
    v-if="previewWrapper.requirementPreviewVisiable"
    :visible="previewWrapper.requirementPreviewVisiable"
    :requirementId="Number(previewWrapper.requirementPreviewId)"
    @update:visible="
      (val) => {
        previewWrapper.requirementPreviewVisiable = val
      }
    "
    @close="(val) => handleEditClose(val, 'requirement')"
  />

  <!-- 迭代视图弹窗 -->
  <IterationView
    v-if="previewWrapper.iterationPreviewVisiable"
    :visible="previewWrapper.iterationPreviewVisiable"
    :iterationId="Number(previewWrapper.iterationPreviewId)"
    @update:visible="(val) => (previewWrapper.iterationPreviewVisiable = val)"
    @close="(val) => handleEditClose(val, 'iteration')"
  />
  <!-- 里程碑视图弹窗 -->
  <!-- <MileStoneView
    v-if="previewWrapper.milestonePreviewVisiable"
    :visible="previewWrapper.milestonePreviewVisiable"
    :milestoneId="Number(previewWrapper.milestonePreviewId)"
    @update:visible="
      (val) => {
        previewWrapper.milestonePreviewVisiable = val
      }
    "
  /> -->

  <!-- 任务创建弹窗 -->
  <TaskCreate
    v-if="taskCreateVisible"
    :visible="taskCreateVisible"
    :proId="Number(currentProject?.id)"
    @update:visible="(val) => (taskCreateVisible = val)"
    @reload="doInitForAll()"
  />
  <!-- 需求创建弹窗 -->
  <RequirementCreate
    v-if="requirementCreateVisible"
    :visible="requirementCreateVisible"
    :proId="Number(currentProject?.id)"
    @update:visible="(val) => (requirementCreateVisible = val)"
    @reload="doInitForAll()"
  />
  <!-- 迭代创建弹窗 -->
  <IterationCreate
    v-if="iterationCreateVisible"
    :visible="iterationCreateVisible"
    :proId="Number(currentProject?.id)"
    @update:visible="(val) => (iterationCreateVisible = val)"
    @reload="doInitForAll()"
  />
  <!-- 里程碑创建弹窗 -->
  <MilestoneCreate
    v-if="milestoneCreateVisible"
    :visible="milestoneCreateVisible"
    :proId="Number(currentProject?.id)"
    @update:visible="(val) => (milestoneCreateVisible = val)"
    @reload="doInitForAll()"
  />
</template>

<style scoped>
.tasks-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative; /* 为绝对定位的footer提供参考 */
}

.tasks-content {
  flex: 1;
  min-height: 0;
  padding-bottom: 64px; /* 为底部工具栏留出空间 */
}

.table-section {
  height: 100%;
  position: relative;
  padding-right: 16px;
}

.table-footer {
  position: absolute;
  bottom: 32px;
  left: 0;
  right: 0;
  height: 64px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-top: 1px solid var(--color-border);
  background: var(--color-bg-2);
}

.milestone-btn {
  color: var(--color-text-2) !important;
  padding: 4px 12px !important;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.milestone-btn:hover {
  color: rgb(var(--primary-6)) !important;
  background-color: var(--color-fill-2) !important;
}

.milestone-btn.active {
  color: rgb(var(--primary-6)) !important;
  background-color: var(--color-primary-light-1) !important;
}
.total-info {
  color: var(--color-text-2);
  font-size: 14px;
}

/* 添加以下样式 */
:deep(.arco-table) {
  /* 设置表格边框 */
  border: 1px solid var(--color-border);
}

:deep(.arco-table-th) {
  /* 设置表头边框 */
  border-right: 1px solid var(--color-border) !important;
}

:deep(.arco-table-td) {
  /* 设置单元格边框 */
  border-right: 1px solid var(--color-border) !important;
}

:deep(.arco-table-tr) {
  /* 设置行边框 */
  border-bottom: 1px solid var(--color-border);
}

/* 添加行背景色样式 */
:deep(.arco-table-tr) {
  /* 设置行边框 */
  border-bottom: 1px solid var(--color-border);
}

/* 迭代行背景色 */
:deep(.arco-table-tr[class*='iteration']) {
  background-color: rgb(var(--primary-1)) !important;
}

/* 需求行背景色 */
:deep(.arco-table-tr[class*='requirement']) {
  background-color: var(--color-fill-2) !important;
}

/* 任务行背景色 */
:deep(.arco-table-tr[class*='task']) {
  /* 使用默认的斑马线背景色 */
}

/* 斑马线样式调整 */
:deep(.arco-table-tr:nth-child(even)) {
  background-color: var(--color-fill-1);
}

/* 鼠标悬停效果 */
:deep(.arco-table-tr:hover) {
  background-color: var(--color-fill-3) !important;
}

/* 选中行效果 */
:deep(.arco-table-tr-checked) {
  background-color: var(--color-primary-light-1) !important;
}

/* 确保选中状态的背景色优先级最高 */
:deep(.arco-table-tr.arco-table-tr-checked),
:deep(.arco-table-tr.arco-table-tr-checked:nth-child(even)) {
  background-color: var(--color-primary-light-1) !important;
}

/* 表格响应式样式 */
:deep(.arco-table) {
  width: 100%;
  min-width: 800px; /* 设置最小宽度，防止内容过于挤压 */
}

:deep(.arco-table-container) {
  height: 100%;
  overflow: auto;
}

/* 固定列样式优化 */
:deep(.arco-table-fixed-left) {
  box-shadow: 6px 0 6px -4px rgba(0, 0, 0, 0.15);
}

/* 表格单元格文本溢出处理 */
:deep(.arco-table-td) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 标题列特殊处理，允许换行 */
:deep(.arco-table-td[class*='column-title']) {
  white-space: normal;
  word-break: break-word;
}

/* 在小屏幕下优化固定列的显示 */
@media screen and (max-width: 1200px) {
  :deep(.arco-table-td),
  :deep(.arco-table-th) {
    padding: 8px !important;
  }
}

@media screen and (max-width: 992px) {
  :deep(.arco-table) {
    min-width: 600px;
  }
}

/* 类型前缀样式 */
.type-prefix {
  display: inline-flex;
  align-items: center; /* 垂直居中 */
  margin-right: 4px;
}

.type-prefix.iteration {
  color: rgb(var(--primary-6));
  background-color: var(--color-primary-light-1);
}

.type-prefix.requirement {
  color: rgb(var(--warning-6));
  background-color: var(--color-warning-light-1);
}

.type-prefix.task {
  color: rgb(var(--success-6));
  background-color: var(--color-success-light-1);
}

/* 添加标题单元格的样式 */
.title-cell {
  position: relative;
  display: flex;
  align-items: center; /* 垂直居中 */
  width: 100%;
  padding: 4px 8px;
  min-height: 32px;
}

.title-content {
  flex: 1;
  display: flex;
  align-items: center;
  min-width: 0; /* 允许内容收缩 */
}

.title-left {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0; /* 允许内容收缩 */
  flex: 1;
}

/* 确保标题文字不会超出 */
.title-left span {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  min-width: 0; /* 允许文字收缩 */
}

.editing-indicator {
  position: absolute; /* 改为绝对定位 */
  top: -20px; /* 向上偏移以显示在单元格上方 */
  left: 54px; /* 靠左对齐 */
  z-index: 10; /* 确保显示在内容上层 */
}

.editing-tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 0 8px;
  height: 20px; /* 稍微降低高度使其更紧凑 */
  background-color: var(--color-primary-light-1);
  color: rgb(var(--primary-6));
  border: 1px solid var(--color-primary-light-3);
  border-radius: 10px; /* 增加圆角效果 */
  white-space: nowrap;
  font-size: 12px; /* 减小字体大小 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加轻微阴影 */
  max-width: 128px; /* 添加最大宽度限制 */
}

/* 添加文本溢出处理 */
.editing-tag :deep(.arco-tag-content) {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100px; /* 为头像预留空间 */
}

/* 编辑按钮容器 */
.edit-button {
  position: absolute;
  right: 4px;
  opacity: 0;
  transition: opacity 0.2s;
}

.title-cell:hover .edit-button {
  opacity: 1;
}

/* 编辑输入框样式 */
.edit-input {
  width: 100%;
  margin-right: 24px; /* 为编辑按钮留出空间 */
}

.header-section {
  display: flex;
  justify-content: start;
  align-items: center;
  width: 100%;
}

.left-section {
  display: flex;
  align-items: center;
}

.online-users-section {
  display: flex;
  align-items: center;
}

.avatar-group {
  display: flex;
  align-items: center;
}

.overlapped-avatars {
  display: flex;
  align-items: center;
  padding: 0 4px;
}

.more-users {
  margin-left: 4px;
  color: var(--color-text-2);
  font-size: 16px;
}

.online-users-list {
  max-height: 300px;
  overflow-y: auto;
  padding: 4px;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 4px 8px;
  gap: 8px;
}

.user-item:hover {
  background-color: var(--color-fill-2);
  border-radius: 4px;
}

/* 图标样式统一 */
:deep(.arco-icon) {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

/* 确保头像垂直居中 */
:deep(.arco-avatar) {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 确保编辑标签容器不被截断 */
:deep(.arco-table-td) {
  overflow: visible !important;
}

:deep(.arco-table-cell) {
  overflow: visible !important;
}

/* 状态单元格样式 */
.status-cell {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.dropdown-trigger {
  opacity: 0;
  transition: opacity 0.2s;
}

.status-cell:hover .dropdown-trigger {
  opacity: 1;
}

.status-options {
  padding: 4px;
  min-width: 60px;
}

/* 确保下拉按钮不会影响布局 */
.dropdown-trigger .arco-btn {
  padding: 0 4px;
}

/* 负责人单元格样式 */
.owner-cell {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  padding: 4px;
}

/* 下拉触发器样式 */
.dropdown-trigger {
  position: absolute;
  right: 4px;
  opacity: 0;
  transition: opacity 0.2s;
}

/* 悬浮时显示下拉触发器 */
.owner-cell:hover .dropdown-trigger {
  opacity: 1;
}

/* 成员选项样式 */
.member-options {
  padding: 4px;
  min-width: 160px;
  max-height: 300px;
  overflow-y: auto;
}

/* 成员选项按钮样式 */
.member-options .arco-btn {
  width: 100%;
  justify-content: flex-start;
  padding: 4px 8px;
}

.member-options .arco-btn:hover {
  background-color: var(--color-fill-2);
}

/* 确保单元格内容可见 */
:deep(.arco-table-td) {
  padding: 0 !important;
}

/* 优先级单元格样式 */
.priority-cell {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  padding: 4px;
}

.priority-cell:hover .dropdown-trigger {
  opacity: 1;
}

.priority-options {
  padding: 4px;
  min-width: 80px;
}

/* 时间列样式 */
.time-cell {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  padding: 4px;
}

.time-cell:hover .dropdown-trigger {
  opacity: 1;
}

/* 时间选择器容器样式 */
.date-picker-container {
  padding: 4px;
  min-width: 240px;
}

.operations-cell {
  display: flex;
  justify-content: center;
  align-items: center;
}

.operations-cell :deep(.arco-btn) {
  padding: 0 4px;
}
</style>
